package com.bite.forum.controller;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.Board;
import com.bite.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Tag(name = "板块接口")
@RequestMapping("/board")
@RestController
public class BoardController {
    @Value("${forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;

    @Operation(summary = "板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList(){
        log.info("首页板块个数为：" + indexBoardNum);
        //查询
        List<Board> result = boardService.selectByNum(indexBoardNum);
        if(result == null){
            result = new ArrayList<>();
        }
        return AppResult.success(result);
    }

    @Operation(summary = "根据帖子id获取帖子信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@Schema(description = "帖子id") @RequestParam("id") @NotNull Long id) {
        // 调用Service
        Board board = boardService.selectById(id);
        // 对查询结果进行校验
        if (board == null || board.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 返回结果
        return AppResult.success(board);
    }
}
